package application

import (
	"context"
	"errors"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/internal/interface/runner"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/util/goroutine"
	"time"
)

func NewCaddy() runner.Runner {
	return func(ctx context.Context) (<-chan struct{}, error) {
		var ch = make(chan struct{}, 1)

		var caddy = GetCaddyApplication()
		var state, _, _, _, _ = caddy.State()

		if application.NotInstall == state {
			return nil, errors.New("Caddy服务未安装，请先执行初始化，如需帮助可通过命令: hui-hui init --help获取")
		}

		if application.VersionNotEffect == state {
			return nil, errors.New("Caddy服务版本过低，无法使用，请先执行强制初始化，如需帮助可通过命令: hui-hui init --help获取")
		}

		if application.Installed != state {
			return nil, errors.New("Caddy服务状态无效，请先执行强制初始化，如需帮助可通过命令: hui-hui init --help获取")
		}

		if err := caddy.Start(ctx, true); nil != err {
			return nil, err
		}

		logger.GetLogger().Sugar().Info("Caddy服务已启动")

		goroutine.Go(func() {
			<-ctx.Done()
			var deadline, cancel = context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()

			if err := caddy.Stop(deadline); nil != err {
				logger.GetLogger().Sugar().Errorf("停止Caddy服务失败，失败原因: %s", err)
			} else {
				logger.GetLogger().Sugar().Info("Caddy服务已退出")
			}

			ch <- struct{}{}
			close(ch)
		})

		return ch, nil
	}
}
